//
//  WatchViewController.m
//  LiveStar
//
//  Created by 漪珊 on 2016/12/21.
//  Copyright © 2016年 apple. All rights reserved.
//

#import "WatchViewController.h"
#import "LivingfunctionView.h"
#import "FansPresentView.h"
#import "LSIMPlatform.h"
#import "LSPLayMgr.h"
#import "FPresentListModel.h"
#define kFansPresentHeight 240

@interface WatchViewController ()<LivingfunctionViewDelegate,FansPresentViewDelegate>
{
    TXLivePlayer *_txLivePlayer;
    TIMManager *_timmanager;
    TIMGroupManager *_timgroupmanager;
    FansPresentView *_fansPresentView;
    AVIMMsgHandler *_immsgHandler;
    NSMutableArray *_presentArray;
}
@property (nonatomic, strong) LivingfunctionView *functionView;
@property (nonatomic, strong) UIView *videoView;
/**
   送礼界面弹出状态
 */
@property (nonatomic, assign) BOOL presentState;
@end

@implementation WatchViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setUpUI];
    //登录IM
    [self registeIM];
    
    [self setMsgHandler];
    
    [self starPullStream];
    
}

#pragma mark -- 礼物列表
- (void)sendPresentlistRequset {
    NSString *userType = KString([[LSUserInfoManager sharedManager] currentUserInfo].u_type);
    NSDictionary *dict = @{
                           @"udid":User_ID,
                           @"token":TOKEN,
                           @"type":userType
                           };
    NSString *urlString = [TEST_URL stringByAppendingString:kGifList];
    [NetworkTools postReqeustWithParams:dict UrlString:urlString successBlock:^(id responseObject) {
        if ([KString(responseObject[@"code"]) isEqualToString:@"200"]) {
            NSArray *array = responseObject[@"data"][@"list"];
            for (NSDictionary *presentDict in array) {
                FPresentListModel *model = [[FPresentListModel alloc] initWithDict:presentDict];
                model.isSelected = NO;
                [_presentArray addObject:model];
            }
            [self initPresentViewWithBalance:KString(responseObject[@"data"][@"u_balance"])];
            [_fansPresentView.presentCollectionView reloadData];
        }
    } failureBlock:^(NSError *error) {
        
    } showHUD:NO];
}

#pragma mark -- 粉丝送礼
- (void)fansSendPresentRequestWithCid:(NSString *)cid {
    NSDictionary *dict = @{
                           @"udid":User_ID,
                           @"token":TOKEN,
                           @"channel":_roomid,
                           @"suid":self.s_uid,
                           @"cid":cid,
                           };
    NSString *urlString = [TEST_URL stringByAppendingString:kFansSendGif];
    [self showHUDInView:self.view title:@""];
    [NetworkTools postReqeustWithParams:dict UrlString:urlString successBlock:^(id responseObject) {
        [self hideHUD];
        if ([KString(responseObject[@"code"]) isEqualToString:@"200"]) {
            NSString *tipMsg = @"";
            tipMsg = responseObject[@"data"][@"message"];
            UserModel *model = [[LSUserInfoManager sharedManager] currentUserInfo];
            LSMsgModel *msgModel = [[LSMsgModel alloc] init];
            msgModel.userName = model.u_nickname;
            msgModel.userMsg  = tipMsg;
            msgModel.userHeadImageUrl = model.u_avatar;
            msgModel.msgType = AVIMCMD_Fans_Present;
            NSString *position;
            switch ([cid intValue]) {
                case 101:
                    position = @",0";
                    break;
                case 102:
                    position = @",1";
                    break;
                case 103:
                    position = @",2";
                    break;
                case 104:
                    position = @",3";
                    break;
                case 105:
                    position = @",4";
                    break;
                case 106:
                    position = @",5";
                    break;
                    
                default:
                    break;
            }
            NSString *msg = [tipMsg stringByAppendingString:position];
            [_immsgHandler sendMessage:AVIMCMD_Fans_Present userId:User_ID nickName:model.u_nickname headPic:model.u_avatar msg:msg Level:@"0"];
            [self.functionView.msgTableView bulletNewMsg:msgModel];
        }
    } failureBlock:^(NSError *error) {
        [self hideHUD];
    } showHUD:NO];

}
#pragma mark --  设置AVIMMsgHandler
- (void)setMsgHandler {
    _immsgHandler = [[AVIMMsgHandler alloc] init];
    _immsgHandler.groupId = self.chatroomid;
    _immsgHandler.chatRoomConversation = [[TIMManager sharedInstance] getConversation:TIM_GROUP receiver:self.chatroomid];
    [self.functionView setMsgHandler:_immsgHandler];
}

#pragma mark -- IM

- (void)registeIM {
    LSIMPlatform *lsIMPlatform = [[LSIMPlatform alloc] init];
//    [lsIMPlatform initIMSDK];
    [lsIMPlatform loginIMSDKWithIMUserModelWithSucc:^{
        [[TIMGroupManager sharedInstance] JoinGroup:self.chatroomid msg:@"Apply Join Group" succ:^(){
            NSLog(@"Join Succ");
            UserModel *model = [[LSUserInfoManager sharedManager] currentUserInfo];
            [_immsgHandler sendEnterLiveRoomMessage:model.udid nickName:model.u_nickname headPic:model.u_avatar Level:KString(model.level)];
            [self.functionView EnterRoomAnimationWithUsername:model.u_nickname Level:KString(model.level)];
        }fail:^(int code, NSString * err) {
            NSLog(@"code=%d, err=%@", code, err);
        }];
    } Fail:^(int code, NSString *msg) {
        
    }];
}



#pragma mark -- 观看端请求
- (void)sendLeaveRoomRequest {
    NSDictionary *dict = @{
                           @"udid":User_ID,
                           @"token":TOKEN,
                           @"channel":self.roomid,
                           @"group":self.roomid,
                           @"status":@"3" //3表示离开直播间
                           };
    NSString *urlString = [TEST_URL stringByAppendingString:kWatchlive];
    [NetworkTools postReqeustWithParams:dict UrlString:urlString successBlock:^(id responseObject) {
        [[TIMGroupManager sharedInstance] QuitGroup:self.chatroomid succ:^() {
            UserModel *model = [[LSUserInfoManager sharedManager] currentUserInfo];
            [_immsgHandler sendQuitLiveRoomMessage:model.udid nickName:model.u_nickname headPic:model.u_avatar Level:KString(model.level)];
            [self dismissViewControllerAnimated:YES completion:nil];
            NSLog(@"succ");
        } fail:^(int code, NSString* err) {
            [self dismissViewControllerAnimated:YES completion:nil];
            NSLog(@"failed code: %d %@", code, err);
        }];
        
    } failureBlock:^(NSError *error) {
    } showHUD:NO];
}



#pragma mark -- 看直播
- (void)starPullStream {
    _txLivePlayer = [[TXLivePlayer alloc] init];
    //用 setupVideoWidget 给播放器绑定决定渲染区域的view，其首个参数 frame 在 1.5.2 版本后已经废弃
    [_txLivePlayer setupVideoWidget:CGRectMake(0, 0, 0, 0) containView:self.videoView insertIndex:0];
    //使用 startPlay 即可开始播放，如果是直播的话我们推荐 FLV 协议
    [_txLivePlayer startPlay:self.pullUrl type:PLAY_TYPE_LIVE_FLV];

}

#pragma mark -- 离开直播间
- (void)leaveRoom {
    if(_txLivePlayer != nil){
        _txLivePlayer.delegate = nil;
        [_txLivePlayer stopPlay];
        [_txLivePlayer removeVideoWidget];
    }
    [self sendLeaveRoomRequest];
}

- (void)setUpUI{
    
    UIView *videoView = [[UIView alloc] initWithFrame:self.view.bounds];
    videoView.backgroundColor = [UIColor darkGrayColor];
    self.videoView = videoView;
    [self.view addSubview:videoView];
    
    LivingfunctionView *functionView = [[NSBundle mainBundle] loadNibNamed:@"LivingfunctionView" owner:self options:nil].lastObject;
    functionView.delegate = self;
    functionView.frame = self.view.bounds;
    functionView.backgroundColor = [UIColor clearColor];
    functionView.cameraBtn.hidden = YES;
    functionView.redPaperBtn.hidden = YES;
    functionView.faceBtn.hidden = YES;
    [functionView.StarPhoto sd_setImageWithURL:[NSURL URLWithString:[[LSUserInfoManager sharedManager] currentUserInfo].u_avatar] placeholderImage:kPlACE_ICON];
    self.functionView = functionView;
    [self.view addSubview:functionView];
    
    self.presentState = NO;
    _presentArray = [NSMutableArray arrayWithCapacity:1];
    
}

#pragma mark -- LivingfunctionViewDelegate
- (void)functionClickWithSign:(NSString *)sign FunctionView:(LivingfunctionView *)functionView {
    if ([sign isEqualToString:@"1"]) {//发消息
        [self.functionView msgInputView];
    } else if ([sign isEqualToString:@"2"]){//送礼物
        [self sendPresentlistRequset];
        self.presentState = YES;
    } else {//离开直播间
        [self leaveRoom];
    }
}

//初始化礼物界面
- (void)initPresentViewWithBalance:(NSString *)balance {
    _fansPresentView = [[NSBundle mainBundle] loadNibNamed:@"FansPresentView" owner:self options:nil].lastObject;
    _fansPresentView.delegate = self;
    _fansPresentView.blanceLabel.text = balance;
    _fansPresentView.frame = CGRectMake(0, kSCREEN_HEIGHT - kFansPresentHeight, kSCREEN_WIDTH, kFansPresentHeight);
    _fansPresentView.presentArray = _presentArray;
    [self.view addSubview:_fansPresentView];

}

//关闭礼物界面
- (void)ClosePresent {
    [_fansPresentView removeFromSuperview];
}
//主播离开房间
- (void)starLiveroom {
    UIAlertController *alertVc = [UIAlertController alertControllerWithTitle:@"提示" message:@"主播已关闭直播" preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *action1 = [UIAlertAction actionWithTitle:@"确认" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self dismissViewControllerAnimated:YES completion:nil];
    }];
    [alertVc addAction:action1];
    [self presentViewController:alertVc animated:YES completion:nil];
}

#pragma mark -- FansPresentDelegate (送礼)
- (void)sendPresentToStarWithCid:(NSString *)cid {
    if ([cid isEqualToString:@""]) {
        [self showTitle:@"请先选择礼物!"];
        return;
    }
    [self fansSendPresentRequestWithCid:cid];
}

- (void)CloseFansPresentView {
    if (self.presentState) {
        [self ClosePresent];
        self.presentState = NO;
    }

}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
